local jiezhen = fk.CreateSkill{
  name = "sclan__jiezhen",
}

Fk:loadTranslationTable{
  ["sclan__jiezhen"] = "解阵",
  [":sclan__jiezhen"] =   "一名角色的结束阶段，你可以交换两张「石兵」的位置。"
  .."然后若其中位置相连的红色「石兵」不少于「石兵」总数的一半，你可以使用一张「石兵」；"
  .."准备阶段，若所有「石兵」的点数严格递增或严格递减，你获得所有「石兵」。",

  ["#sclan__jiezhen-exchange"] = "解阵：交换两张「石兵」的位置",
}

jiezhen:addEffect(fk.EventPhaseStart, {
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(jiezhen.name) and #player:getPile("sclan__shibing") > 0 then
      if target ~= player then
        return data.phase == Player.Finish
      elseif data.phase == Player.Start then
        return (table.every(player:getPile("sclan__shibing"), function (c1, i)
          return i == 1 or Fk:getCardById(c1).number <= Fk:getCardById(player:getPile("sclan__shibing")[i-1]).number
        end) or table.every(player:getPile("sclan__shibing"), function (c1, i)
          return i == 1 or Fk:getCardById(c1).number >= Fk:getCardById(player:getPile("sclan__shibing")[i-1]).number
        end))
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if data.phase == Player.Finish then
      return room:askToSkillInvoke(player, { skill_name = jiezhen.name })
    else
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if data.phase == Player.Finish then
      local cards = room:askToChooseCards(player, {
        flag = { card_data = {{ "sclan__shibing", player:getPile("sclan__shibing") },} },
        min = 2,
        max = 2,
        target = player,
        skill_name = jiezhen.name,
        prompt = "#sclan__jiezhen-exchange"
      })
      local new = {}
      for _, c in ipairs(player:getPile("sclan__shibing")) do
        local e = table.contains(cards, c) and cards[(3 - table.indexOf(cards, c))] or c
        table.insert(new, e)
      end
      local special = player.special_cards
      special.sclan__shibing = new
      room:setPlayerProperty(player, "special_cards", special)

      local count = 0
      for _, c in ipairs(new) do
        if Fk:getCardById(c).color == Card.Red then
          count = count + 1
        else
          count = 0
        end
        if count >= (#new / 2) then
          break
        end
      end
      if count >= (#new / 2) then
        room:askToUseRealCard(player, {
          pattern = tostring(Exppattern{ id = new }),
          skill_name = jiezhen.name,
          extra_data = { expand_pile = new, bypass_times = true }
        })
      end
    else
      room:obtainCard(player, player:getPile("sclan__shibing"), true, fk.ReasonJustMove, player, jiezhen.name)
    end
  end
})

return jiezhen